package com.central.gateway.error;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.DefaultErrorAttributes;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.validation.BindingResult;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 自定义异常属性
 * @author zouzhihui
 */
@Slf4j
public class SelfDefaultErrorAttributes implements ErrorAttributes {

    private static final String ERROR_ATTRIBUTE = SelfDefaultErrorAttributes.class.getName() + ".ERROR";

    private final boolean includeException;

    private final String STATUS = "status";

    /**
     * Create a new {@link DefaultErrorAttributes} instance that does not include the
     * "exception" attribute.
     */
    public SelfDefaultErrorAttributes() {
        this(false);
    }

    /**
     * Create a new {@link DefaultErrorAttributes} instance.
     * @param includeException whether to include the "exception" attribute
     */
    public SelfDefaultErrorAttributes(boolean includeException) {
        this.includeException = includeException;
    }

    @Override
    public Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {
        Map<String, Object> errorAttributes = new LinkedHashMap<>();
        Throwable error = getError(request);
        if (error instanceof BusinessException) {
            errorAttributes.put(STATUS, 200);
            BusinessException businessException = (BusinessException) error;
            errorAttributes.put("nResult", businessException.getCode());
            errorAttributes.put("vcResult", businessException.getErrorMessage());
        } else if (error instanceof ResponseStatusException) {
            errorAttributes.put(STATUS, ((ResponseStatusException) error).getStatus().value());
            errorAttributes.put("nResult", 160002);
            errorAttributes.put("vcResult", "路径不存在");
            log.error("[160002]" + error.getMessage(), error);
        } else {
            errorAttributes.put(STATUS, 500);
            errorAttributes.put("nResult", 160000);
            errorAttributes.put("vcResult", "系统异常");
            log.error("[160000]" + error.getMessage(), error);
        }
        handleException(errorAttributes, determineException(error), includeStackTrace);
        return errorAttributes;
    }

    private Throwable determineException(Throwable error) {
        if (error instanceof ResponseStatusException) {
            return (error.getCause() != null) ? error.getCause() : error;
        }
        return error;
    }

    private void addStackTrace(Map<String, Object> errorAttributes, Throwable error) {
        StringWriter stackTrace = new StringWriter();
        error.printStackTrace(new PrintWriter(stackTrace));
        stackTrace.flush();
        errorAttributes.put("trace", stackTrace.toString());
    }

    private void handleException(Map<String, Object> errorAttributes, Throwable error, boolean includeStackTrace) {
        if (this.includeException) {
            errorAttributes.put("exception", error.getClass().getName());
        }
        if (includeStackTrace) {
            addStackTrace(errorAttributes, error);
        }
        if (error instanceof BindingResult) {
            BindingResult result = (BindingResult) error;
            if (result.hasErrors()) {
                errorAttributes.put("errors", result.getAllErrors());
            }
        }
    }

    @Override
    public Throwable getError(ServerRequest request) {
        return (Throwable) request.attribute(ERROR_ATTRIBUTE)
                .orElseThrow(() -> new IllegalStateException("Missing exception attribute in ServerWebExchange"));
    }

    @Override
    public void storeErrorInformation(Throwable error, ServerWebExchange exchange) {
        exchange.getAttributes().putIfAbsent(ERROR_ATTRIBUTE, error);
    }
}
